import React, { FC, useState } from "react";
import { ComponentType } from "../login";
import IconMap from "@/components/IconMap";
import { Button } from "antd";
import { loginRules } from "@/utils/rules/loginRule";
const SMSLogin: FC<ComponentType> = (props: ComponentType) => {
  const { FormItem, Input, form } = props;
  const [disabled, setDisabled] = useState(true);
  const [statusCrueent, setStatusCrueent] = useState(false);
  const TIME_SISTY = 60;
  const [timer, setTimer] = useState(TIME_SISTY);

  const sentCode = () => {
    setStatusCrueent(true);
    setDisabled(true);
    //这里提前减去一秒
    setTimer((v) => v - 1);
    const t = setInterval(() => {
      setTimer((v) => {
        if (v === 1) {
          setStatusCrueent(false);
          setDisabled(false);
          clearInterval(t);
          return TIME_SISTY;
        }
        return --v;
      });
    }, 1000);
  };

  async function phoneChangeHanle() {
    try {
      await form.validateFields(["phonenumber"]);
      setDisabled(false);
    } catch (err) {
      setDisabled(true);
    }
  }
  return (
    <>
      <FormItem name="phonenumber" rules={loginRules.phoneRules} hasFeedback>
        <Input
          placeholder="请输入手机号码"
          prefix={IconMap.PhoneOutlined}
          onChange={phoneChangeHanle}
        ></Input>
      </FormItem>
      <FormItem name="code" rules={loginRules.codeRules} hasFeedback>
        <Input
          placeholder="请输入验证码"
          prefix={IconMap.CodepenOutlined}
          maxLength={6}
          addonAfter={
            <Button
              block
              className="!border-0 !bg-transparent !h-full"
              disabled={disabled}
              onClick={sentCode}
            >
              {!statusCrueent ? "获取验证码" : `${timer}可重新获取`}
            </Button>
          }
        ></Input>
      </FormItem>
    </>
  );
};

export default SMSLogin;
